package com.simple.mq.sdk.client;

import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.util.function.Consumer;

/**
 * 项目: simple-mq
 * <p>
 * 功能描述:
 *
 * @author: WuChengXing
 * @create: 2023-09-04 14:35
 **/
@Slf4j(topic = "SimpleMQClient")
public class SimpleMQClient extends WebSocketClient {

    /**
     * client的名称
     */
    private final String name;

    /**
     * client 类型，0代表consumer，1代表producer
     */
    private int type;

    /**
     * 供外部类用来处理接受消息的接口函数
     */
    private Consumer<String> onMessageAction;

    /**
     * 同一个包内访问
     *
     * @param serverUri
     * @param name
     * @param type
     */
    public SimpleMQClient(URI serverUri, String name, int type) {
        super(serverUri);
        this.name = name;
        this.type = type;
    }

    public void setOnMessageAction(Consumer<String> onMessageAction) {
        this.onMessageAction = onMessageAction;
    }

    @Override
    public void onOpen(ServerHandshake handshake) {
        log.info("Simple MQ Client Connect: ==> 【{}】", name);
    }

    @Override
    public void onMessage(String message) {
        if (onMessageAction != null) {
            onMessageAction.accept(message);
        }
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        log.warn("Connection closed. code:【{}】, reason: 【{}】, remote: 【{}】", code, reason, remote);
    }

    @Override
    public void onError(Exception ex) {
        log.warn("Connection error:【{}】", ex.getMessage());
    }
}
